let cacheData = require('../cache')
let calUtil = require('../cal')

module.exports = {
  ConfigValue: getConfigValue
}

// rtdb 数据解压间隔时间
const func = {
  second: 1,
  minute: 10,
  hour: 60,
  day: 60 * 60,
  month: 60 * 60,
  year: 60 * 60
}

// 数据来源类型
const srcType = {
  date: function (dateData) {
    let datearr = []
    dateData.map(data => {
      datearr.push({Text: data.date, value: data.date})
    })
    return datearr
  },
  cal: getValueFromTimespan,
  real: getRealValue
}

function getValueFromTimespan (parameter) {
  let tempInterval = 60
  tempInterval = func[parameter.dateFormat]
  return new Promise((resolve, reject) => {
    cacheData.cache.historyData({
      VarName: parameter.name,
      StartTime: parameter.start,
      EndTime: parameter.end,
      Interval: tempInterval
    }).then(result => {
      /* 拆分时间段数据 */
      let temparr = []
      let dataArr = []
      if (parameter.interval === 0) {
        result.map(varValue => {
          temparr.push(varValue.Value)
        })
        dataArr.push({
          date: parameter.name,
          data: temparr
        })
      } else {
        dataArr = IntervalStatistics({data: result, times: parameter.dateArr})
      }
      // 2、分段统计计算
      let resultarr = []
      dataArr.map(tempArr => {
        // let sumss = Math.max.apply(null, tempArr.data)
        let tempValue = 0
        tempValue = calUtil[parameter.type](tempArr.data)
        resultarr.push({
          Text: tempArr.date,
          value: tempValue
        })
      })
      // console.log('%s: filed:%s %s %s data:%s', Date.now(), name, start, end, JSON.stringify(resultarr))
      resolve(resultarr)
    })
  })
}

function getRealValue (parameter) {
  return new Promise((resolve, reject) => {
    cacheData.cache.cacheGetdata(parameter.varname).then(result => {
      if (result.length > 0) {
        let resultdata = []
        if (parameter.type === 'table') {
          parameter.dataArr.map(arr => {
            resultdata.push({value: result[0].Value})
          })
          resolve(resultdata)
        } else {
          resultdata.push({value: result[0].Value})
          resolve(resultdata)
        }
      } else {
        resolve({value: 0})
      }
    })
  })
}

// 根据时间段分片实时数据
function IntervalStatistics (parameter) {
  let times = []
  parameter.times.map(time => {
    times.push({date: time.date, StartTime: time.StartTime, EndTime: time.EndTime, data: []})
  })
  parameter.data.map(tempdata => {
    let tempTime = new Date(tempdata.Time)
    tempTime.setSeconds(-8 * 60 * 60)
    times.map(time => {
      if (tempTime >= time.StartTime && tempTime <= time.EndTime) {
        time.data.push(tempdata.Value)
      }
    })
  })
  return times
}

let dataModule = {
  // point 统计值
  pointData: function (pointConfigData, startTime, endTime) {
    let resultArrData = {}
    let pointPromise = []
    let pointkey = []
    return new Promise((resolve, reject) => {
      pointConfigData.map(point => {
        pointkey.push(point.fieldName)
        if (point.src.type === 'real') {
          pointPromise.push(srcType[point.src.type]({varname: point.src.varName}))
        } else if (point.src.type === 'cal') {
          if (point.src.timeType === undefined) {
            pointPromise.push(srcType[point.src.type]({
              name: point.src.varName,
              start: startTime,
              end: endTime,
              interval: 0,
              dateFormat: 'hour',
              type: point.src.func
            }))
          } else {
            let tempTime = time(point.src.timeType, point.src.timeValue)
            pointPromise.push(srcType[point.src.type]({
              name: point.src.varName,
              start: tempTime.StartTime,
              end: tempTime.EndTime,
              interval: 0,
              dateFormat: point.src.timeType,
              type: point.src.func
            }))
          }
        }
      })
      Promise.all(pointPromise).then(results => {
        results.map((r, i) => {
          if (r.length > 0) {
            resultArrData[pointkey[i]] = r[0].value
          }
        })
        resolve(resultArrData)
      })
    })
  },
  // table 统计
  tableData: function (config, tablecfg, startTime, endTime) {
    return new Promise((resolve, reject) => {
      let tempPromise = []
      let tempkyes = []
      let tempList = {}
      tempList[tablecfg.fieldName] = []
      // 查找第一个 date
      let firstdate = {}
      for (let key in tablecfg.src) {
        let tempconfg = tablecfg.src[key]
        if (tempconfg.type === 'date') {
          firstdate = tempconfg
          break
        }
      }
      let dateData = intervalValue(firstdate, config.dateFormat, startTime, endTime)
      let temprowData = {}
      for (let key in tablecfg.src) {
        let tempconfg = tablecfg.src[key]
        if (tempconfg.type === 'cal' && tempconfg.timeType === undefined) {
          tempkyes.push(key)
          // tempPromise.push(getValueFromTimespan(tempconfg.name, StartTime, EndTime, tablecfg.src.date.interval, config.dateFormat, tempconfg.func, dateData))
          tempPromise.push(srcType[tempconfg.type]({
            name: tempconfg.varName,
            start: startTime,
            end: endTime,
            interval: firstdate.interval,
            dateFormat: config.dateFormat,
            type: tempconfg.func,
            dateArr: dateData
          }))
        } else if (tempconfg.type === 'cal') {
          tempkyes.push(key)
          let tempTime = time(tablecfg.src.timeType, tablecfg.src.timeValue)
          // tempPromise.push(getValueFromTimespan(tablecfg.src.name, tempTime.StartTime, tempTime.EndTime,
          //   0, tablecfg.src.timeType, tablecfg.src.func))
          tempPromise.push(srcType[tempconfg.type]({
            name: tempconfg.varName,
            start: tempTime.StartTime,
            end: tempTime.EndTime,
            interval: 0,
            dateFormat: config.dateFormat,
            type: tempconfg.func,
            dateArr: dateData
          }))
        } else if (tempconfg.type === 'real') {
          tempkyes.push(key)
          tempPromise.push(srcType[tempconfg.type]({varname: tempconfg.varName, type: 'table', dataArr: dateData}))
        } else if (tempconfg.type === 'date') {
          temprowData[key] = srcType[tempconfg.type](dateData)
        }
      }
      Promise.all(tempPromise).then(results => {
        results.map((r, i) => {
          temprowData[tempkyes[i]] = r
        })
        tempList[tablecfg.fieldName] = temprowData
        resolve(tempList)
      })
    })
  },
  // 多table 统计
  mutiTable: function (config, tableList, startTime, endTime) {
    return new Promise((resolve, reject) => {
      let tempPromise = []
      tableList.map(v => {
        tempPromise.push(this.tableData(config, v, startTime, endTime))
      })
      Promise.all(tempPromise).then(results => {
        resolve(results)
      })
    })
  }
}

// 解析配置获取统计值 
function getConfigValue (config, StartTime, EndTime) {
  let pointConfigData = []
  let tableConfigData = []
  // 区分point table
  config.items.map(item => {
    if (item.type === 'point' && item.src !== undefined) {
      pointConfigData.push({
        fieldName: item.data,
        src: item.src
      })
    } else if (item.type === 'table') {
      tableConfigData.push({
        fieldName: item.data,
        src: item.src
      })
    }
  })
  return new Promise((resolve, reject) => {
    Promise.all([dataModule.pointData(pointConfigData, StartTime, EndTime), dataModule.mutiTable(config, tableConfigData, StartTime, EndTime)]).then(results => {
      let temp = results[0]
      let tableList = results[1]
      tableList.map(tableResult => {
        for (let key in tableResult) {
          temp[key] = []
          for (let fieldName in tableResult[key]) {
            tableResult[key][fieldName].map((t, index) => {
              if (temp[key][index] === undefined) {
                temp[key][index] = {}
              }
              temp[key][index][fieldName] = t.value === undefined ? t.Value : t.value
            })
          }
        }
      })
      console.log(JSON.stringify(temp))
      resolve(temp)
    })
  })
}

// 解析timeType  开始与结束时间
const timeType = {
  day: function (value) {
    let nowtime = new Date()
    let starttime = new Date(nowtime.toDateString())
    let endtime = new Date(nowtime.toDateString())
    if (value === 0) {
      return {StartTime: starttime, EndTime: nowtime}
    } else {
      starttime.setHours(value * -24)
      endtime.setHours((value - 1) * -24)
      endtime.setSeconds(-1)
      return {StartTime: starttime, EndTime: endtime}
    }
  },
  week: function (value) {
    let nowtime = new Date()
    let starttime = new Date(nowtime.toDateString())
    let endtime = new Date(nowtime.toDateString())
    let dayindex = nowtime.getDay() === 0 ? 7 : nowtime.getDay()
    if (value === 0) {
      starttime.setHours((dayindex - 1) * -24)
      return {StartTime: starttime, EndTime: nowtime}
    } else {
      starttime.setHours(((value * 7) + (dayindex - 1)) * -24)
      endtime.setHours((dayindex - 1) * -24)
      endtime.setHours((value - 1) * 7 * -24)
      endtime.setSeconds(-1)
      return {StartTime: starttime, EndTime: endtime}
    }
  },
  month: function (value) {
    let nowtime = new Date()
    let starttime = new Date(nowtime.toDateString())
    let endtime = new Date(nowtime.toDateString())
    let dayindex = nowtime.getDay() === 0 ? 7 : nowtime.getDay()
    if (value === 0) {
      starttime.setDate(1)
      return {StartTime: starttime, EndTime: nowtime}
    } else {
      // if(nowtime.getMonth() )
      starttime.setHours(((value * 7) + (dayindex - 1)) * -24)
      endtime.setHours((dayindex - 1) * -24)
      endtime.setHours((value - 1) * 7 * -24)
      endtime.setSeconds(-1)
      return {StartTime: starttime, EndTime: endtime}
    }
  }
}

function time (timeType, timeValue) {
  if (timeType === 'day') {
    // let nowDate = Date.now()
    return {StartTime: '2017-10-18 17:00:00', EndTime: '2017-10-19 10:00:00'}
  } else if (timeType === 'week') {
    return {StartTime: '2017-10-18 17:00:00', EndTime: '2017-10-19 10:00:00'}
  } else if (timeType === 'month') {
    return {StartTime: '2017-10-18 17:00:00', EndTime: '2017-10-19 10:00:00'}
  } else if (timeType === 'year') {
    return {StartTime: '2017-10-18 17:00:00', EndTime: '2017-10-19 10:00:00'}
  } else if (timeType === 'minute') {
    return {StartTime: '2017-10-18 17:00:00', EndTime: '2017-10-19 10:00:00'}
  } else if (timeType === 'hour') {
    return {StartTime: '2017-10-18 17:00:00', EndTime: '2017-10-19 10:00:00'}
  }
  return undefined
}

// 根据配置切割的时间
function intervalValue (config, dateFormat, StartTime, EndTime) {
  let starttime = new Date(StartTime)
  let endtime = new Date(EndTime)
  let data = []
  let firstTime = new Date(StartTime)
  if (config.interval === undefined ||
    (dateFormat !== 'minute' & dateFormat !== 'hour' & dateFormat !== 'day' & dateFormat !== 'month')) {
    data.push({date: endtime.toLocaleTimeString(), StartTime: firstTime, EndTime: endtime, data: []})
    return data
  }
  while (true) {
    let tempdate = starttime.setSeconds(config.interval)
    if (tempdate > endtime.setSeconds(0)) {
      if (data.length === 0) {
        data.push({date: endtime.toLocaleString(), StartTime: firstTime, EndTime: endtime, data: []})
      }
      return data
    } else if (data.length > 1000) {
      return data
    }
    if (dateFormat === 'minute' || dateFormat === 'hour') {
      data.push({date: starttime.toLocaleString(), StartTime: firstTime, EndTime: starttime, data: []})
    } else if (dateFormat === 'day') {
      data.push({date: starttime.toLocaleDateString(), StartTime: firstTime, EndTime: starttime, data: []})
    } else if (dateFormat === 'month') {
      data.push({date: starttime.getMonth(), StartTime: firstTime, EndTime: starttime, data: []})
    }
    firstTime = new Date(starttime)
    starttime = new Date(starttime)
  }
}
